<template>
  <div>
    <SplitPanel>
      <template #left-content>
        <a-card size="small" style="height: 100%;" title="组织机构">
          <Tree v-model:expandedKeys="state.expandedKeys" auto-expand-parent :tree-data="state.deptTree"
            @select="onTreeSelect">
          </Tree>
        </a-card>
      </template>
      <template #right-content>
        <a-card size="small" style="height: 100%;" title="经办人">
          <SchemaForm>
          </SchemaForm>
        </a-card>
      </template>
    </SplitPanel>
  </div>
</template>

<script setup lang="tsx">
import { ref, reactive, onMounted } from 'vue';
import { message, Tree } from 'ant-design-vue';
import type { TreeDataItem } from '@/core/permission/utils';
import { SplitPanel } from '@/components/basic/split-panel';
import { getDeptList } from '@/api/system/dept';
import { formatDept2Tree } from '@/core/permission/utils';
import { useForm } from '@/components/core/schema-form';
import { deptHandledSchemas } from './formSchemas'
import { addDeptHandled, updateDeptHandled, getDeptHandledInfoByDeptId } from '@/api/workorder/depthandled'
import { any, string } from 'vue-types';

defineOptions({
  name: 'deptHandled',
});

interface State {
  expandedKeys: string[];
  departmentIds: string[];
  deptTree: TreeDataItem[];
}


const deptListLoading = ref(false);
const deptId = ref(String);

const state = reactive<State>({
  expandedKeys: [],
  departmentIds: [],
  deptTree: [],
});
let deptHandled = reactive({});


/**
 * 获取部门列表
 */
const fetchDeptList = async () => {
  deptListLoading.value = true;
  const dept = await getDeptList().finally(() => (deptListLoading.value = false));
  state.deptTree = formatDept2Tree(dept);
  state.expandedKeys = [...state.expandedKeys, ...state.deptTree.map((n) => String(n.key))];
};

/**
 * 点击部门
 */
const onTreeSelect = async (selectedKeys: string[]) => {
  state.departmentIds = selectedKeys;
  deptHandled = await getDeptHandledInfoByDeptId(selectedKeys[0])
  deptId.value = selectedKeys[0]
  dynamicFormRef?.setFieldsValue({
    deptId: selectedKeys[0],
    name: deptHandled?.name,
    telephone: deptHandled?.telephone
  })
};

// 初始化表单内容
const [SchemaForm, dynamicFormRef] = useForm({
  labelWidth: 100,
  schemas: deptHandledSchemas,
  showSubmitButton: true,
  submitButtonOptions: {
    text: '保存',
    disable: true
  },
  submitFunc: async () => {
    let formData = {
      ...dynamicFormRef?.getFieldsValue(),
      deptId: deptId.value,
      id: deptHandled?.id
    }
    if (!formData.deptId) {
      message.success('部门不可为空！');
      return;
    }
    // 数据保存
    let data = await (deptHandled?.id ? updateDeptHandled : addDeptHandled)(formData);
    deptHandled = data
  },
  showResetButton: true,
});

onMounted(() => {
  fetchDeptList();
});
</script>

<style></style>
